package com.pactera.asmp.server.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: asmpserver
 * @Package: com.pactera.asmp.server.common.utils
 * @ClassName: EmailUtils
 * @Author: lvzhiqiang
 * @Description: Email工具类创建Email Template
 * @Date: 2019/7/26 12:27
 * @Version: 1.0
 */
public class EmailUtils {
    private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class);


    /**
     * @Method getIntenetAddressList
     * @Description getIntenetAddressList
     * @param: [emails]
     * @return: javax.mail.internet.InternetAddress[]
     * @auther: lzq
     * @date: 2019/7/25 17:52
     */
    public static InternetAddress[]  getIntenetAddressList(String[] emails){
        List<InternetAddress> list = new ArrayList<InternetAddress>();
        for (int i = 0; i < emails.length; i++) {
            try {
                list.add(new InternetAddress(emails[i]));
            } catch (AddressException e) {
                logger.error("getIntenetAddressList AddressException :", e.toString());
            }
        }
        InternetAddress[] address = list.toArray(new InternetAddress[list.size()]);
        return address;
    }

    /**
     * @Method
     * @Description 创建Thymeleaf模板
     * @param: [dataMap, templatesName, templateEngine]
     * @return: String
     * @auther: lzq
     * @date: 2019/7/26 7:09
     */
    public static String createTemplates(Map<String,Object> dataMap, String templatesName, TemplateEngine templateEngine){
        Context context = new Context();
        context.setVariables(dataMap);
        String emailText = templateEngine.process(templatesName,context);
        logger.info("createTemplates emailText:", emailText);
        return emailText;
    }

    /**
     * @Method addImageResource
     * @Description addImageResource
     * @param: [imagePath, htmlTag, multipart]
     * @return: void
     * @throws IOException 
     * @auther: lzq
     * @date: 2019/7/26 12:37
     */
    public static void addImageResource(String imagePath,String htmlTag, MimeMultipart multipart) throws MessagingException, IOException {
        MimeBodyPart imagePart = new MimeBodyPart();
        Resource resource = new  ClassPathResource(imagePath);
        File imageFile = File.createTempFile("temp", ".png");

        InputStream inputStream= resource.getInputStream();
        OutputStream outputStream = new FileOutputStream(imageFile);
        byte[] buffer =new byte[1024];
        int length;
        while((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
        inputStream.close();
        outputStream.close();
        DataSource fds = new FileDataSource(imageFile);
        imagePart.setDataHandler(new DataHandler(fds));
        imagePart.setHeader("Content-ID","<"+htmlTag+">");
        imagePart.setHeader("Content-Type", "image/png");
        imagePart.setDisposition(MimeBodyPart.INLINE);
        multipart.addBodyPart(imagePart);
    }

    public static void addAttchments(String[] filePath, String templateInfo, MimeMultipart multipart, MimeMessage mimeMessage, MimeMessageHelper messageHelper) throws MessagingException{
        BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
        mdp.setContent(templateInfo, "text/html;charset=UTF-8");// 给BodyPart对象设置内容和格式/编码方式
        multipart.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
        if (filePath != null) {
            // 把mm作为消息对象的内容
            MimeBodyPart filePart;
            FileDataSource filedatasource;
            // 逐个加入附件
            for (int j = 0; j < filePath.length; j++) {
                filePart = new MimeBodyPart();
                filedatasource = new FileDataSource(filePath[j]);
                filePart.setDataHandler(new DataHandler(filedatasource));
                try {
                    filePart.setFileName(MimeUtility.encodeText(filedatasource.getName()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                multipart.addBodyPart(filePart);
            }
        }
        mimeMessage.setContent(multipart);
    }


    public static void setRecipients(String[] address, MimeMessage mimeMessage, Message.RecipientType type) throws MessagingException{
        InternetAddress[] toAddress = EmailUtils.getIntenetAddressList(address);
        mimeMessage.setRecipients(type, toAddress);
    }

}
